#include<iostream>
#include<map>
using namespace std;

//详见 http://c.biancheng.net/view/7174.html 

int main(){
    map<string, int> word_count;
    word_count["anna"] = 1;//如果元素不存在则会新增一个key，顺序容器则不会

    //插入map
    word_count.insert(make_pair("james2", 2));
    //或者用原始的方法
    word_count.insert(map<string, int>::value_type("james3", 3));
    //或者typedef
    typedef map<string, int>::value_type valType;
    word_count.insert(valType("james4", 4));

    //获取元素，
    //可以直接用下标word_count["james"]但是如果不存在，则会新增一个key
    int er = word_count["none_key"];

    //所以获取前最好先判断下
    //方法1，用count()
    int num = 0;
    if (word_count.count("james2"))
    {
        num = word_count["james2"];
    }

    //方法2，用find()
    int num2 = 0;
    map<string, int>::iterator it = word_count.find("james2");
    if(it != word_count.end()){
        num2 = it->second;//等同于 (*it).second
    }

    cout << "num:" << num << " num2: " << num2 << endl;
    
    //删除元素
    if (word_count.erase("james3"))
    {
        cout << "erase success return 1" <<endl;
    }else{
        cout << "erase failed return 0" << endl;
    }
    
    //遍历
    map<string, int>::const_iterator map_it = word_count.begin();
    while (map_it != word_count.end())
    {
        cout << map_it->first << "->" << (*map_it).second << endl;
        map_it++;
    }
    
}